<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use app\models\{Region, BusinessArea};

function gettime()
{
    $stime = strtotime("09:30:00");
    $etime = strtotime("21:00:00");
    $time = date('H:i:s', rand($stime, $etime));
    if ($time > date('Y-m-d H:i', time() - 60 * 60)) {
        gettime();
    } else {
        return $time;
    }
}


function rekey($model, $qz)
{
    $code = createKey($qz);
    $row = $model->where('code', $code)->find();
    if ($row) {
        return rekey($model, $qz);
    } else {
        return $code;
    }
}

//生成推荐码
function createKey($qz)
{
    $max = 8 - mb_strlen($qz);
    if ($max <= 0) {
        $code = rand(11111111, 9999999);
    } else {
        $micode = pow(10, $max - 1);
        $macode = 9 * pow(10, $max - 1);
        $code = $qz . rand($micode, $macode);
    }
    return $code;
}

//微信通知
function wechattest($touser = '', $data1 = '', $data2 = '', $data3 = '', $data4 = '', $data5 = '', $data6 = '')
{
    $config = config('wechat2.');
    $app = Factory::officialAccount($config);
    $send_data = [
        'template_id' => '-5vdQde7MY9gb2TwjAiM9HZnXxNLzpzg-HR9fNtxe1A', // 所需下发的订阅模板id
        'touser' => $touser,     // 接收者（用户）的 openid
        'miniprogram' => [
            'appid' => 'wx547b5ab1f4500ecf',
            'pagepath' => '/pages/horseman/index',
        ],
        'data' => [
            'first' => [
                'value' => $data1
            ],
            'keyword1' => [
                'value' => $data2
            ],
            'keyword2' => [
                'value' => $data3
            ],
            'keyword3' => [
                'value' => $data4
            ],
            'keyword4' => [
                'value' => $data5
            ],
            'remark' => [
                'value' => $data6
            ],
        ],
    ];
    $rm = $app->template_message->send($send_data);
    return $rm;
}

function getImage($url, $save_dir = '', $filename = '', $type = 0)
{
    if (trim($url) == '') {
        return array('file_name' => '', 'save_path' => '', 'error' => 1);
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (trim($filename) == '') { //保存文件名
        $ext = strrchr($url, '.');
        // if ($ext != '.gif' && $ext != '.jpg' && $ext != '.png') {
        //     return array('file_name' => '', 'save_path' => '', 'error' => 3);
        // }
        $filename = time() . rand(1, 100000) . $ext;
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return array('file_name' => '', 'save_path' => '', 'error' => 5);
    }
    //获取远程文件所采用的方法 
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $img = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
    }
    //$size=strlen($img);
    //文件大小 
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $img);
    fclose($fp2);
    unset($img, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}

//生成推荐码
function createOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function reordersn($model)
{
    $code = createOrdersn();
    $row = $model->where('ordersn', $code)->find();
    if ($row) {
        reordersn();
    } else {
        return $code;
    }
}


//生成订单号
function createPayOrdersn()
{
    $code = time() . rand(100000, 999999);
    return $code;
}

function repayorder($model)
{
    $code = createPayOrdersn();
    $row = $model->where('paymentid', $code)->find();
    if ($row) {
        repayorder();
    } else {
        return $code;
    }
}

//生成推荐码
function createCode()
{
    $code = rand(10000000, 99999999);
    return $code;
}

function recode($user)
{
    $code = createCode();
    $row = $user->where('code', $code)->find();
    if ($row) {
        recode();
    } else {
        return $code;
    }
}

function rsa_asr($rsa, $data = [])
{
    $MAX_DECRYPT_BLOCK = 172;
    $ct = "";
    $str = strlen($data);
    $offSet = 0;
    $endOffSet = $MAX_DECRYPT_BLOCK;
    while ($str - $offSet > 0) {
        if ($str - $offSet > $MAX_DECRYPT_BLOCK) {
            $bufTmp = substr($data, $offSet, $endOffSet);
            $ct .= $rsa->privDecrypt($bufTmp);
        } else {
            $bufTmp = substr($data, $offSet, $str);
            $ct .= $rsa->privDecrypt($bufTmp);
        }
        $offSet += $MAX_DECRYPT_BLOCK;
    }
    return json_decode($ct, true);
}



function unique()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    );
    return $d;
}

//1.数组转xml
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<$key>$val</$key>";
        } else
            $xml .= "<$key><![CDATA[$val]]></$key>";
    }
    $xml .= "</xml>";
    return $xml;
}

//2.xml转数组
function xmlToArray($xml)
{
    $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $arr;
}


/**

 * excel表格导出

 * @param string $fileName 文件名称

 * @param array $headArr 表头名称

 * @param array $data 要导出的数据

 * @author static7  */

function excelExport($fileName = '', $headArr = [], $data = [])
{
    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";
    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    //设置表头
    $key = 0;
    //print_r($headArr);exit;
    foreach ($headArr as $v) {
        //注意，不能少了。将列数字转换为字母\
        $colum = \PHPExcel_Cell::stringFromColumnIndex($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { //行写入
        $span = 0;
        foreach ($rows as $keyName => $value) { // 列写入
            $j = \PHPExcel_Cell::stringFromColumnIndex($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle($date);
    //设置字体大小
    $objPHPExcel->getDefaultStyle()->getFont()->setSize(14);
    //设置单元格宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
    //设置默认行高
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(23);
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}


function api_curl($url, $data = false, $ispost = 0)
{
    $headers = array();
    array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $data = http_build_query($data);
        if ($data) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $data);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    $response = json_decode($response, true);
    return $response;
}

//方法二
/*判断函数，$arr放入多边形各个顶点的坐标，
$t为判断点的位置，$n为顶点坐标的个数-1；
若点在多边形内则返回1，否则返回0；
*/
function inpolygon($arr, $t, $n)
{
    for ($i = 0; $i <= $n; $i++) {
        $arr[$i][0] -= $t[0];
        $arr[$i][1] -= $t[1];
    }
    $t1 = $arr[0][0] >= 0 ? ($arr[0][1] >= 0 ? 0 : 3) : ($arr[0][1] >= 0 ? 1 : 2);
    for ($sum = 0, $i = 1; $i <= $n; $i++) {
        if (!$arr[$i][0] && !$arr[$i][1]) {
            break;
        }
        $f = $arr[$i][1] * $arr[$i - 1][0] - $arr[$i][0] * $arr[$i - 1][1];
        if (!$f && $arr[$i - 1][0] * $arr[$i][0] <= 0 && $arr[$i - 1][1] * $arr[$i][1] <= 0) {
            break;
        }
        $t2 = $arr[$i][0] >= 0 ? ($arr[$i][1] >= 0 ? 0 : 3) : ($arr[$i][1] >= 0 ? 1 : 2);
        if ($t2 == ($t1 + 1) % 4) {
            $sum += 1;
        } else if ($t2 == ($t1 + 3) % 4) {
            $sum -= 1;
        } else if ($t2 == ($t1 + 2) % 4) {
            if ($f > 0) $sum += 2;
            else $sum -= 2;
        }
        $t1 = $t2;
    }
    if ($i <= $n || $sum) {
        return 1;  //点在多边形内则返回1
    }
    return 0;  //点在多边形外则返回0
}

##$isagent 0返回地址id 1返回地址代理  2返回行政名称 3地址id+代理id
function getlatlon($lat = 0, $lng = 0)
{
    $lat  = (float)$lat;
    $lng  = (float)$lng;
    $arr = [
        'street' => 0,
        'street' => 0,
        'area' => 0,
        'city' => 0,
        'province' => 0,
        'agentid' => 0
    ];
    $sql =  "MBRContains(ST_PolygonFromText(ar.ploygongeo),st_geomfromtext('Point(" . $lng . " " . $lat . ")'))>0";
    $businessarea = (new BusinessArea())->alias('ar')->join('business a', 'ar.businessid = a.id')
        ->where(['a.status' => 1, 'ar.type' => 5])->field('ar.id,ar.street,ar.businessid,substring(ar.ploygongeo,10,length(ploygongeo)-11) as ploygongeo')
        ->where($sql)->select();
    $businesss = [];
    foreach($businessarea as $business){
        //php再次判断点位
        $ploygongeo = explode(',', $business['ploygongeo']) ?? [];
        if (count($ploygongeo) > 0) {
            foreach ($ploygongeo as $k => &$ploygongeos) {
                $ploygongeos = explode(' ', $ploygongeos) ?? [0, 0];
                if (count($ploygongeos) != 2) {
                    unset($ploygongeo[$k]);
                }
            }
        }
        if (count($ploygongeo) > 0) {
            $ploygongeo = array_values($ploygongeo);
        }
        //没有点重新判断
        if (count($ploygongeo) > 0) {
            $center = [$lng, $lat];
            $isin = inpolygon($ploygongeo, $center, count($ploygongeo) - 1);
            //点在多边形外边
            if (!empty($isin)) {
                $businesss[$business['businessid']] = $business['businessid'];
            }
        }
    }
    $businesss = array_values($businesss);
    return $businesss;

}
